<template>
  <div class="about">
    <h2>msg: {{ msg }}</h2>
    <hr>
    <button @click="update">更新</button>
    <h1>{{ x }}:{{ y }}</h1>
    <h2 v-if="loading">LOADING...</h2>
    <h2 v-else-if="errorMsg">{{ errorMsg }}</h2>
    <!-- <ul v-else>
      <li>id: {{result.id}}</li>
      <li>name: {{result.name}}</li>
      <li>distance: {{result.distance}}</li>
    </ul> -->

    <ul v-for="p in result" :key="p.id">
      <li>{{ p.id }}</li>
      <li>{{ p.title }}</li>
      <li>{{ p.price }}</li>
    </ul>
    <!-- <img v-if="result" :src="result[0].url" alt=""> -->
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  onMounted,
  onUpdated,
  onUnmounted,
  onBeforeMount,
  onBeforeUpdate,
  onBeforeUnmount,
  watch
} from 'vue'
import useMousePosition from '@/hooks/useMousePosition'
import useRequest from '@/hooks/useRequest'

// 地址数据接口
interface AddressResult {
  id: number;
  name: string;
  distance: string;
}

// 产品数据接口
interface ProductResult {
  id: string;
  title: string;
  price: number;
}

export default defineComponent({
  name: 'About',
  beforeCreate() {
    console.log('beforeCreate')
  },
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted() {
    console.log('mounted')
  },
  beforeUpdate() {
    console.log('beforeUpdate')
  },
  updated() {
    console.log('updated')
  },
  beforeUnmount() {
    console.log('beforeUnmount')
  },
  unmounted() {
    console.log('unmounted')
  },
  setup() {
    const msg = ref('abc')
    const update = () => {
      msg.value += '--'
    }
    onBeforeMount(() => {
      console.log('--onBeforeMount')
    })

    onMounted(() => {
      console.log('--onMounted')
    })

    onBeforeUpdate(() => {
      console.log('--onBeforeUpdate')
    })

    onUpdated(() => {
      console.log('--onUpdated')
    })

    onBeforeUnmount(() => {
      console.log('--onBeforeUnmount')
    })

    onUnmounted(() => {
      console.log('--onUnmounted')
    })
    const {x, y} = useMousePosition()
    // const {Loading, result, errorMsg} = useRequest<AddressResult>('/data/address.json')
    const {loading, result, errorMsg} = useRequest<ProductResult[]>('/data/products.json')
    watch(result, () => {
      if (result.value) {
        console.log(result.value.length) // 有提示
      }
    })
    return {
      msg,
      update,
      x,
      y,
      loading,
      result,
      errorMsg
    }
  }
})
</script>
